#include "ModulePattern.h"
#include "ModuleConstants.h"

namespace modx {

	ModulePattern::ModulePattern() {
		patternContents.clear();
	}
	
	ModulePattern::ModulePattern(unsigned short* noteTable, unsigned char numChannels, unsigned char* rawPattern) {
		int i = 0, j = 0, n = 0;
		ModuleNote note;
		short period;
		unsigned char* patPtr = rawPattern;
		
		 
		for(i = 0; i < 64; i++) {
			patternContents.push_back(std::vector<ModuleNote>());
			
			for(j = 0; j < numChannels; j++) {
				note.sampleNumber = (patPtr[0] & 0xF0) + (patPtr[2] >> 4);
				if(note.sampleNumber == 0) note.sampleNumber = NO_SAMPLE;
				else note.sampleNumber--;
				period = ((patPtr[0] & 0xF) << 8) + patPtr[1];
				note.effectNumber = patPtr[2] & 0xF;
				note.effectParam = patPtr[3];
				
				note.noteNumber = NO_NOTE;
				for(n = 0; n < MAX_NOTES; n++) {
					if(period >= noteTable[n]) {
						note.noteNumber = n;
						break;
					}
				}
				
				patternContents[i].push_back(note);
				patPtr += 4;
			}
		}
	}
	
	std::vector<ModuleNote>* ModulePattern::getRow(unsigned char rowNumber) {
		try {
			return &patternContents.at(rowNumber);
		} catch(std::out_of_range e) {
			throw;
		}
	}
}
